package com.example.user.service.impl;

import com.example.model.pojo.User;
import com.example.model.utils.JwtUtils;
import com.example.model.utils.UserHolder;
import com.example.user.mapper.UserMapper;
import com.example.model.pojo.dto.ChangePasswordDTO;
import com.example.model.pojo.dto.LoginDTO;
import com.example.model.pojo.vo.LoginVO;
import com.example.model.pojo.vo.UserInfoVO;
import com.example.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * 用户服务实现类
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final JwtUtils jwtUtils;

    @Override
    public LoginVO login(LoginDTO loginDTO) {
        // 根据用户名或学号或教师工资号查询用户
        User user = getUserByUsernameOrStudentIdOrTeacherId(
                loginDTO.getUsername(), loginDTO.getStudentId(), loginDTO.getTeacherId());

        // 验证用户是否存在
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        if (user.getPassword() == null) {
            if (!Objects.equals(loginDTO.getPassword(), user.getStudentId())) {
                throw new RuntimeException("初始化密码与学号不匹配");
            }
            if (!Objects.equals(loginDTO.getPassword(), user.getTeacherId())){
                throw new RuntimeException("初始化密码与教师工资号不匹配");
            }
        }

        if (!Objects.equals(loginDTO.getPassword(), user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 生成JWT令牌
        String token = jwtUtils.generateToken(user);

        // 将用户信息保存到线程本地存储
        UserHolder.set(user);

        // 构建返回结果
        LoginVO loginVO = new LoginVO();
        loginVO.setToken(token);
        loginVO.setUserInfo(convertToUserInfoVO(user));

        return loginVO;
    }

    @Override
    public boolean logout(Integer userId) {
        // 从线程本地存储中移除用户信息
        UserHolder.remove();
        // 这里可以添加token黑名单等逻辑
        return true;
    }

    @Override
    public boolean changePassword(Integer userId, ChangePasswordDTO changePasswordDTO) {
        // 获取用户信息
        User user = getUserById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证旧密码是否正确
        if (!user.getPassword().equals(changePasswordDTO.getOldPassword())) {
            throw new RuntimeException("旧密码错误");
        }
        // 更新密码
        int result = userMapper.updatePassword(userId, changePasswordDTO.getNewPassword());
        return result > 0;
    }

    @Override
    public UserInfoVO getUserInfo(Integer userId) {
        User user = getUserById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return convertToUserInfoVO(user);
    }

    @Override
    public User getUserByUsernameOrStudentIdOrTeacherId(String username, String studentId, String teacherId) {
        // 确保至少有一个查询条件
        if (!StringUtils.hasText(username) && !StringUtils.hasText(studentId) && !StringUtils.hasText(teacherId)) {
            throw new RuntimeException("查询条件不能为空");
        }
        return userMapper.selectByNameOrStudentIdOrTeacherId(username, studentId, teacherId);
    }

    @Override
    public User getUserById(Integer userId) {
        if (userId == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        return userMapper.selectById(userId);
    }

    @Override
    public UserInfoVO convertToUserInfoVO(User user) {
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfoVO);
        return userInfoVO;
    }
}